from datetime import datetime
from flask import render_template, session, redirect, url_for
from . import main
from .forms import NameForm
from .. import db
from ..models import User

@main.route('/', methods=['GET', 'POST'])
@main.route('/index', methods=['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        # old_name = session.get('name')
        # if old_name is not None and old_name != form.name.data:
        #     flash('你改变了输入的名字！', 'danger')
        # session['name'] = form.name.data
        user = User.query.filter_by(username=form.name.data).first()
        if user is None:
            user = User(username=form.name.data)
            db.session.add(user)
            db.session.commit()
            session['known'] = False
        else:
            session['known'] = True
        session['name'] = form.name.data
        # if app.config['FLASKY管理员']:
        #     send_email(app.config['FLASKY管理员'], '新朋友加入', 'mail/new_user', user=user)
        form.name.data = ''
        return redirect(url_for('main.index'))
    return render_template('index.html', form = form, name=session.get('name'), known=session.get('known', False), current_time=datetime.utcnow())